// add an event listener for every window
window.addEventListener("load", function() { pageLoadListener.init(); }, false);

window.addEventListener("focus", function() { pageLoadListener.onPageFocus(); }, true);

window.addEventListener("close", function() { pageLoadListener.onCloseBrowser(); }, false);

var pageLoadListener = {
	/* This function initializates the needed event listeners for catching
	the load event */
	init: function() {
		// get the content of the window (even of the tab)
    	var appcontent = document.getElementById("appcontent");   // browser
        
		callDeserialize()

		// add an event listener to the content of every page
    	if(appcontent){ // if the content was found..
			// execute onPageLoad every time it's loaded
			//logMessage('adding the onload listener to the current page');
			setIconColor();
			appcontent.addEventListener("load", this.onPageLoad, true);
		}
  	},

	/* This function will be called every time a load event will be caugth while
	loading a page (inside a window or even a tab) */
  	onPageLoad: function(aEvent) {
    	//var doc = aEvent.originalTarget; // maybe I will need it to filter the incoming events
		saveHTML(window.content.document.location); // URL
  	},

	/* Checks when a page is on focus, aka is read or at least visible to the user */
	onPageFocus: function(eEvent) {
		try{
			//logMessage('page focus: ' + window.content.document.location)
			var pageID = createPageID(window.content.document.body.innerHTML,
				window.content.document.location.href)
			
			callHandleFocus(pageID,
				window.content.document.location,
				window.content.document.body.innerHTML)
				
		}catch(ex){
			// alert('exception in function onPageFocus' + ex)
			// it may happen that we are trying to focus somethign that doesn't have
			// an actual content.
		}
	},
	
	/* When FF gets closed, save the time spent on the remainin open tab */
	onCloseBrowser: function(eEvent) {
		try{
			//alert('closing ' + window.content.document.location)
			callHandleLastFocus()
			callPageInfoSerialize()
		}catch(ex){
			alert('exception in function onCloseBrowser ' + ex)
			// it may happen that we are trying to focus somethign that doesn't have
			// an actual content.
		}
	}
}
